/**
 * @作者:黎谢之
 * @创建时间：2021/7/7
 * @修改时间：2021/7/13
 */
package com.example.senior_bug.Service;

import com.example.senior_bug.EntityClass.*;
import com.example.senior_bug.Repository.*;
import com.example.senior_bug.ToolClass.Result;
import com.example.senior_bug.enm.MsgId;
import com.example.senior_bug.utils.ImageFileUtils;
import com.example.senior_bug.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class CustomerService {

    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private BrandRepository brandRepository;
    @Autowired
    private GoodRepository goodRepository;
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private ConcreteSKURepository concreteSKURepository;
    @Autowired
    private SKURepository skuRepository;

    /*用户注册带头像
     *
     * */
    public Result RegisterWithFaceImage(MultipartFile file, Customer customer) {
        //判断昵称是否重复
        if (customerRepository.existsByName(customer.getName())) {
            return ResultUtils.error(MsgId.NIKENAME_HAVE_BEEN_REGISTER);
        }

        //判断手机号是否已注册
        if ((customer.getPhoneNum() != null) && customerRepository.existsByPhoneNum(customer.getPhoneNum())) {
            return ResultUtils.error(MsgId.PHONENUM_HAVE_BEEN_REGISTER);
        }

        //判断邮箱是否已注册
        if ((customer.getEmail() != null) && customerRepository.existsByEmail(customer.getEmail())) {
            return ResultUtils.error(MsgId.EMAIL_HAVE_BEEN_REGISTER);
        }

        customer.setUuid(UUID.randomUUID().toString().trim().replace("-", ""));//生成UUID

        //存储图片
        Result result = ImageFileUtils.ModifyOrAddImage(file);

        //判断图片存储异常
        switch (result.getCode()) {
            case 23:
                return ResultUtils.error(MsgId.FILE_IS_NULL);
            case 24:
                return ResultUtils.error(MsgId.FILE_TOO_LARGE);
            case 25:
                return ResultUtils.error(MsgId.EXTENSION_IS_INCORRECT);
            case 26:
                return ResultUtils.error(MsgId.FILE_EXCEPTION);
            default:
                break;
        }

        String url = result.getDate().toString();
        customer.setFaceUrl(url);

        Customer customer1 = customerRepository.saveAndFlush(customer);

        if (customerRepository.existsById(customer1.getId())) {
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.REGISTER_FAILED);
        }
    }

    /*用户个人主页
     *
     * */
    public Result getById(int id) {
        //先判断用户是否存在
        if (customerRepository.existsById(id)) {
            return ResultUtils.success(customerRepository.findById(id));
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }

    /*测试函数
     * */
    public Result getAll() {
        return ResultUtils.success(customerRepository.findAll());
    }

    /*用于用户购物车方法
     * 1.传入的用户昵称(CustomerName)
     * 获得商品封装类ConcreteSKU的List
     * 7.13检查无问题
     * */
    public Result GetAllSkuByCustomerName(String CustomerName) {
        //先判断用户是否存在
        if (customerRepository.existsByName(CustomerName)) {
            List<ConcreteSKU> concreteSKUS = new ArrayList<>();
            for (ConcreteSKU item :
                    concreteSKURepository.findAll()) {
                //判断购物车商品对象是否属于该用户
                if (customerRepository.findByName(CustomerName).getId() == item.getCustomerId()) {
                    Brand brand = brandRepository.findById(goodRepository.findById(item.getSku().getGoodId()).getBrandId());
                    //为临时变量赋值
                    item.getSku().setCategoryName(channelRepository.findById
                            (categoryRepository.findById(brand.getCategoryId())
                                    .getChannelId()).getName() + "/" + categoryRepository.findById(brand.getCategoryId()).getName());
                    item.getSku().setBrandName(brand.getName());
                    concreteSKUS.add(item);
                }
            }
            return ResultUtils.success(concreteSKUS);
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }

    /*用户添加购物车方法
     *
     * */
    public Result PutSkuInShoppingCart(int SkuId, int SpecificationIndex, String CustomerName) {
        //先判断用户是否存在
        if (customerRepository.existsByName(CustomerName)) {
            SKU sku = skuRepository.findById(SkuId);//找到商品
            ConcreteSKU concreteSKU = new ConcreteSKU();//新建包装商品(配置)
            Customer customer = customerRepository.findByName(CustomerName);//找到进行添加操作的用户
            concreteSKU.setSku(sku);//赋值
            concreteSKU.setSpecificationIndex(SpecificationIndex);//赋值
            concreteSKU.setCustomerId(customer.getId());//赋值
            ConcreteSKU concreteSKU1 = concreteSKURepository.saveAndFlush(concreteSKU);//保存包装类(下层)
            customer.getShoppingCart().add(concreteSKU1);//添加关系进关系表
            customerRepository.saveAndFlush(customer);//保存用户数据
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.ADD_SHOPPING_CART_FAILED);
        }
    }

    /*用户删除购物车
     *
     * */
    public Result DeleteSkuInShoppingCart(int ConcreteSKUId, String CustomerName) {
        //先判断用户是否存在
        if (customerRepository.existsByName(CustomerName)) {
            //找到对应购物车商品类
            ConcreteSKU concreteSKU = concreteSKURepository.findById(ConcreteSKUId);

            Customer customer = customerRepository.findByName(CustomerName);//找到进行添加操作的用户
            customer.getShoppingCart().remove(concreteSKU);
            customerRepository.saveAndFlush(customer);//保存用户数据
            concreteSKURepository.delete(concreteSKU);
            return ResultUtils.success(true);
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }


    /*用户手机号登录
     * 1.传入的手机号(pNum)
     * 2.传入的加密密码(pwd)
     * 7.13检查无问题
     * */
    public Result LoginByPhone(String pNum, String pwd) {
        //判断该手机号是否已经注册
        if (customerRepository.existsByPhoneNum(pNum)) {
            //获取用户对象
            Customer customer = customerRepository.findByPhoneNum(pNum);
            //判断密码是否正确
            if (customer.getPassWord().equals(pwd)) {

                return ResultUtils.success(customer);
            } else {
                return ResultUtils.error(MsgId.PASSWORD_NOT_CORRECT);
            }

        } else {
            return ResultUtils.error(MsgId.PHONE_NOT_REGISTER);
        }
    }

    /*用户邮箱登录
     * 7.13检查无问题
     * */
    public Result LoginByEmail(String email, String pwd) {
        //判断邮箱是否已经注册
        if (customerRepository.existsByEmail(email)) {
            //找到用户对象
            Customer customer = customerRepository.findByEmail(email);
            //判断密码是否正确
            if (customer.getPassWord().equals(pwd)) {
                return ResultUtils.success(customer);
            } else {
                return ResultUtils.error(MsgId.PASSWORD_NOT_CORRECT);
            }
        } else {
            return ResultUtils.error(MsgId.EMAIL_NOT_REGISTER);
        }
    }


    /*通过用户名获取用户ID
     * 1.用户名(CustomerName)
     * */
    public Result getIdByCustomerName(String CustomerName) {
        //先判断用户是否存在
        if (customerRepository.existsByName(CustomerName)) {
            return ResultUtils.success(customerRepository.findByName(CustomerName).getId());
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }


    /*用户信息修改
     *
     * */
    public Result ModifyTheInfo(MultipartFile file, int id, String name, String phoneNum, String email) {
        //先判断用户是否存在
        if (customerRepository.existsById(id)) {
            //获取用户对象
            Customer customer = customerRepository.findById(id);
            //判断是否修改昵称且昵称不重复
            if (!customer.getName().equals(name) && customerRepository.existsByName(name)) {
                return ResultUtils.error(MsgId.NIKENAME_HAVE_BEEN_REGISTER);
            }
            //判断是否修改电话号码且电话号码不重复
            if (((customer.getPhoneNum() == null && phoneNum != null) || !customer.getPhoneNum().equals(phoneNum))
                    && customerRepository.existsByPhoneNum(phoneNum)) {
                return ResultUtils.error(MsgId.PHONENUM_HAVE_BEEN_REGISTER);
            }
            //判断是否修改邮箱且邮箱不重复
            if (((customer.getEmail() == null && email != null) || !customer.getEmail().equals(email))
                    && customerRepository.existsByEmail(email)) {
                System.out.println(email + "\t" + customer.getEmail());
                return ResultUtils.error(MsgId.EMAIL_HAVE_BEEN_REGISTER);
            }

            //存储图片
            Result result = ImageFileUtils.ModifyOrAddImage(file);

            //判断图片存储报错
            switch (result.getCode()) {
                case 23:
                    return ResultUtils.error(MsgId.FILE_IS_NULL);
                case 24:
                    return ResultUtils.error(MsgId.FILE_TOO_LARGE);
                case 25:
                    return ResultUtils.error(MsgId.EXTENSION_IS_INCORRECT);
                case 26:
                    return ResultUtils.error(MsgId.FILE_EXCEPTION);
                default:
                    break;
            }


            String newUrl = result.getDate().toString();

            customer.setName(name);
            if (email != null) customer.setEmail(email);
            if (phoneNum != null) customer.setPhoneNum(phoneNum);
            customer.setFaceUrl(newUrl);

            Customer customer1 = customerRepository.saveAndFlush(customer);

            if (customer1.getId() == id)
                return ResultUtils.success();
            else
                return ResultUtils.error(MsgId.MODIFY_ERROR);
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }


    /*用户与商家交流列表
     *
     * */
    public Result getAllBusiness(int customerId) {
        //判断用户是否存在
        if (customerRepository.existsById(customerId)) {
            Customer customer = customerRepository.findById(customerId);
            List<Business> businesses = new ArrayList<>();
            for (Business item :
                    customer.getBusinesses()) {
                Business business = new Business();
                //只赋值需要的信息
                business.setStoreName(item.getStoreName());
                business.setFaceUrl(item.getFaceUrl());
                business.setUuid(item.getUuid());
                businesses.add(business);
            }
            return ResultUtils.success(businesses);
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }

    /*用户与一个新的商家联系
     * 7.23修改
     * */
    public Result CommunicateWithNewBusiness(int CustomerId, int BusinessId) {
        //判断用户是否存在
        if (customerRepository.existsById(CustomerId)) {
            //判断添加的商家是否存在
            if (businessRepository.existsById(BusinessId)) {
                Customer customer = customerRepository.findById(CustomerId);
                Business business = businessRepository.findById(BusinessId);

                //当还未交流过时才添加
                if(!customer.getBusinesses().contains(business)) {
                    customer.getBusinesses().add(business);
                    Customer customer1 = customerRepository.saveAndFlush(customer);
                }
                if(!business.getCustomers().contains(customer)) {
                    business.getCustomers().add(customer);
                    Business business1 = businessRepository.saveAndFlush(business);
                }

                return ResultUtils.success(true);
            } else {
                return ResultUtils.error(MsgId.BUSINESS_NOT_FOUND);
            }
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }

    /*用户首页各种订单的数量
     *
     * */
    public Result NumOfOrder(int CustomerId) {
        //先判断用户是否存在
        if (customerRepository.existsById(CustomerId)) {
            int shop = 0;
            int Logistics = 0;
            int Receive = 0;
            int Leasing = 0;
            int Returned = 0;
            int Returning = 0;

            Customer customer = customerRepository.findById(CustomerId);

            //根据不同种类订单赋值
            for (Order item :
                    customer.getOrders()) {
                switch (item.getState()) {
                    case "待发货":
                        Logistics++;
                        break;
                    case "待收货":
                        Receive++;
                        break;
                    case "租赁中":
                        Leasing++;
                        break;
                    case "待归还":
                        Returned++;
                        break;
                    case "已归还":
                        Returning++;
                        break;
                    default:
                        break;
                }
            }
            //获取购物车商品数量
            shop = customer.getShoppingCart().size();

            String result = shop + "|" + Logistics + "|" + Receive + "|" + Leasing + "|" + Returned + "|" + Returning;

            return ResultUtils.success(result);
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }

    /*用户首页的推荐商品
     *
     * */
    public Result getRecommendSku(int CustomerId) {
        //先判断用户是否存在
        if (customerRepository.existsById(CustomerId)) {
            return ResultUtils.success(customerRepository.findById(CustomerId).getRecommendList());
        } else {
            return ResultUtils.error(MsgId.CUSTOMER_NOT_FOUND);
        }
    }
}
